package com.klangner.math.ast;



public class OperatorNode extends Node {

	private String operators[][] = {
		{"+", "-"},
		{"*", "/"},
		{"^"}
	};
	
	private int	priority;
	
	/**
	 * constructor
	 * @param symbol
	 */
	public OperatorNode(Character op){
	
		super(op.toString());
		
	}
	
	/**
	 * constructor
	 * @param symbol
	 */
	public OperatorNode(String text){
	
		super(text);
		
		priority = getOperatorPriority(text);
	}
	
	
	@Override
	public Node transform(Transform t) {
		
		Node node = null;
		Node left = null;
		Node right = null;

		while( null == node || 
				node.getFirstChild() != left ||
				node.getSecondChild() != right)
		{
			node = t.transformOperator(this);

			left = node.getFirstChild();
			right = node.getSecondChild();

			node.transformChildren(t);
		}
		
		return node;
	}
	
	
	/**
	 * Convert node and its children to string
	 */
	public String toString(){

		String 	output;
		
		output = node2String( getFirstChild() );
		
		output += getText();

		output += node2String( getSecondChild() );

		return output;
	}
	
	
	/**
	 * Convert node and its children to string
	 */
	private String node2String(Node node){

		String 	output = "";
		
		
		if(node != null){
			if( node instanceof OperatorNode && 
				((OperatorNode)node).hasLowerPriority(priority) &&
				node.getFirstChild() != null)
			{
				output +=  "(" + node + ")";
			}
			else{
				output +=  node;
			}
		}
		
		return output;
	}
	
	
	/**
	 * Compare priority
	 * @param p
	 * @return
	 */
	private boolean hasLowerPriority(int p) {
		return (priority < p);
	}

	/**
	 * Get operator priority
	 * @param op
	 * @return
	 */
	private int getOperatorPriority(String op){
		
		for(int i = 0; i < operators.length; i++){
			for(int j = 0; j < operators[i].length; j++){
				if(operators[i][j].compareTo(op) == 0)
					return i;
			}
		}
		
		return 0;
	}
	
}
